package org.apache.tomcat.util.digester;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * RulesBase
 *
 * @author chentudong
 * @date 2024/2/19 17:04
 * @since 1.0
 */
public class RulesBase implements Rules {

  /**
   * The set of registered Rule instances, keyed by the matching pattern. Each value is a List
   * containing the Rules for that pattern, in the order that they were originally registered.
   */
  protected HashMap<String, List<Rule>> cache = new HashMap<>();

  /**
   * The Digester instance with which this Rules instance is associated.
   */
  protected Digester digester = null;

  /**
   * The set of registered Rule instances, in the order that they were originally registered.
   */
  protected ArrayList<Rule> rules = new ArrayList<>();

  public Digester getDigester() {
    return digester;
  }

  @Override
  public void setDigester(Digester digester) {
    this.digester = digester;
  }

  /**
   * rules
   *
   * @return List<Rule>
   */
  @Override
  public List<Rule> rules() {
    return this.rules;
  }

  /**
   * add
   *
   * @param pattern pattern
   * @param rule    rule
   */
  @Override
  public void add(String pattern, Rule rule) {
    int patternLength = pattern.length();
    if (patternLength > 1 && pattern.endsWith("/")) {
      pattern = pattern.substring(0, patternLength - 1);
    }
    List<Rule> list = cache.computeIfAbsent(pattern, k -> new ArrayList<>());
    list.add(rule);
    rules.add(rule);
    if (Objects.nonNull(this.digester)) {
      rule.setDigester(this.digester);
    }
  }
}
